| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 
 | #pragma warning(disable:4996)#include<iostream>
 #include<string>
 #include<vector>
 #include<cstdlib>
 #include<algorithm>
 #include<ctime>
 #include<queue>
 #include<map>
 
 using namespace std;
 
 map<char, string> encode;
 
 
 typedef struct Node
 {
 int pri;
 char data;
 Node* left;
 Node* right;
 }Node;
 
 typedef struct
 {
 bool operator()(const Node* a, const Node* b)
 {
 return a->pri > b->pri;
 }
 }NodeCompare;
 
 
 Node datas[] = { { 67, 'A', NULL, NULL }, { 23, 'B', NULL, NULL }, { 13, 'D', NULL, NULL },
 { 19, 'C', NULL, NULL }, { 10, 'E', NULL, NULL }, { 5, 'F', NULL, NULL } };
 
 
 void dfs(Node* n,string code)
 {
 if (n->left == NULL && n->right == NULL && n->data != ' ')
 {
 encode.insert(make_pair(n->data, code));
 cout << n->data << " : " << code << endl;
 return;
 }
 if (n->left != NULL)
 {
 dfs(n->left, code+'0');
 }
 if (n->right != NULL)
 {
 dfs(n->right, code + '1');
 }
 }
 
 string encoding(string s)
 {
 string result = "";
 for (int i = 0; i < s.length(); i++)
 {
 result += encode.find(s[i])->second;
 }
 return result;
 }
 
 string decode(Node* root, string s)
 {
 Node* current = root;
 string result = "";
 for (int i = 0; i < s.length(); i++)
 {
 if (s[i] == '0')
 current = current->left;
 if (s[i] == '1')
 current = current->right;
 
 if (current->left == NULL && current->right == NULL)
 {
 result+=current->data;
 current = root;
 }
 }
 return result;
 }
 
 int main()
 {
 priority_queue<Node*,vector<Node*>, NodeCompare> pq;
 
 for (int i = 0; i < 6; i++)
 {
 Node* target = new Node(datas[i]);
 pq.push(target);
 }
 
 while (pq.size() != 1)
 {
 Node* left = pq.top();
 pq.pop();
 Node* right = pq.top();
 pq.pop();
 
 int newVal = (left->pri) + (right->pri);
 pq.push(new Node({ newVal, ' ', left, right }));
 }
 
 Node* root = pq.top();
 pq.pop();
 
 cout << "encoding list:" << endl;
 dfs(root, "");
 cout << endl << endl;
 
 
 string target = "ABCFFDEFABCBFFEEDDAABAB";
 cout << "original string   ->   "<<target<<endl;
 string result = encoding(target);
 cout << "converted   ->   "<< result<<endl;
 cout << target.size() * 8 << "bit is converted to " << result.size()<<endl<<endl<<endl;
 
 
 cout<<"converted   ->   "<<result<<"\ndecode result  ->  "<<decode(root, result);
 
 return 0;
 }
 
 |